package com.zmy.xcx.interceptor;

import com.zmy.xcx.context.WxUserContext;
import com.zmy.xcx.properties.JwtProperties;
import com.zmy.xcx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtTokenWxUserInterceptor implements HandlerInterceptor {
    private final JwtProperties jwtProperties;

    /**
     * 效验jwt
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断拦截的是Controller方法还是其他资源
        if(!(handler instanceof HandlerMethod)){
            //不是Controller方法直接放行
            return true;
        }
        //写死openid,默认每次操作都是openid=user用户
        String openid = "user";
        //保存当前线程的用户上下文
        WxUserContext.setCurrentOpenid(openid);
        log.info("当前用户openid:{}",openid);
        //直接放行
        return true;
        //3.效验token
        /*try {
            log.info("拦截器获取到的token:{}",token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            String openid = claims.get("openid").toString();
            //保存当前线程的用户上下文
            WxUserContext.setCurrentOpenid(openid);
            log.info("当前用户openid:{}",openid);
            //4.通过，放行
            return true;
        } catch (Exception e) {
            //token验证失败
            log.error("token验证失败:{}",e.getMessage());
            //不通过，响应状态码401
            response.setStatus(401);
            response.getWriter().write("Token validation failed"); // 直接返回错误信息
            return false;
        }*/

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WxUserContext.removeCurrentOpenid();
    }
}
